package cn.stylefeng.roses.kernel.ca.server.core.loginuser;

import cn.hutool.extra.servlet.ServletUtil;
import cn.stylefeng.roses.kernel.ca.api.CaLoginUserApi;
import cn.stylefeng.roses.kernel.ca.api.CaSessionManagerApi;
import cn.stylefeng.roses.kernel.ca.api.exception.CaServerException;
import cn.stylefeng.roses.kernel.ca.api.exception.enums.CaServerExceptionEnum;
import cn.stylefeng.roses.kernel.ca.api.expander.CaServerConfigExpander;
import cn.stylefeng.roses.kernel.ca.api.pojo.sso.CaLoginUser;
import cn.stylefeng.roses.kernel.cache.api.CacheOperatorApi;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录用户相关的service
 *
 * @author fengshuonan
 * @date 2021/1/21 16:53
 */
public class LoginUserServiceImpl implements CaLoginUserApi {

    private CaSessionManagerApi caSessionManagerApi;

    private CacheOperatorApi<CaLoginUser> cacheOperatorApi;

    public LoginUserServiceImpl(CaSessionManagerApi caSessionManagerApi, CacheOperatorApi<CaLoginUser> cacheOperatorApi) {
        this.caSessionManagerApi = caSessionManagerApi;
        this.cacheOperatorApi = cacheOperatorApi;
    }

    @Override
    public String getUserCaToken() {

        // 获取当前http请求
        HttpServletRequest request = HttpServletUtil.getRequest();

        // 从cookie中获取token
        Cookie cookie = ServletUtil.getCookie(request, CaServerConfigExpander.getCookieName());

        // cookie中没有token，则用户没有在CA有会话信息
        if (cookie == null) {
            throw new CaServerException(CaServerExceptionEnum.COOKIE_IS_NULL);
        }

        // 获取cookie的值
        return cookie.getValue();
    }

    @Override
    public CaLoginUser getLoginUser() {

        // 获取用户的token
        String token = getUserCaToken();

        // 获取session中该token对应的用户
        CaLoginUser caLoginUser = caSessionManagerApi.getCaSession(token);

        // session为空抛出异常
        if (caLoginUser == null) {
            throw new CaServerException(CaServerExceptionEnum.CA_SESSION_EXPIRED, token);
        }

        // 设置用户当前的token
        caLoginUser.setCaToken(token);

        return caLoginUser;
    }

    @Override
    public void stashSsoLoginCode(String ssoLoginCode, CaLoginUser caLoginUser) {
        cacheOperatorApi.put(ssoLoginCode, caLoginUser);
    }

    @Override
    public CaLoginUser destroySsoLoginCode(String ssoLoginCode) {
        CaLoginUser caLoginUser = cacheOperatorApi.get(ssoLoginCode);

        // 如果登录用户为空
        if (caLoginUser == null) {
            throw new CaServerException(CaServerExceptionEnum.LOGIN_CODE_USER_IS_NULL);
        }

        cacheOperatorApi.remove(ssoLoginCode);
        return caLoginUser;
    }

}
